<?php

namespace App\Model\Rbac;

use App\Model\Model;

/**
 * @property int $id
 * @property int $deleted_at
 * @property int $role_id 角色id
 * @property int $route_id 路由id
 */
class RoleRouteModel extends Model
{

    // 角色 <=> 路由
    protected ?string $table = 'role_route';

    protected function buildQuery(array $params = [])
    {
        $where[] = ['deleted_at', 0];
        if (!empty($params['role_id'])) {
            $where[] = ['role_id', $params['role_id']];
        }
        if (!empty($params['route_id'])) {
            $where[] = ['route_id', $params['route_id']];
        }
        return $this->where($where);
    }

    public function addMany($roleId, array $routeIds)
    {
        $add = [];
        foreach (array_unique($routeIds) as $routeId) {
            $add[] = [
                'deleted_at' => 0,
                'role_id' => $roleId,
                'route_id' => $routeId,
            ];
        }
        return $this->insertOrIgnore($add);
    }

    /**
     * @param $roleId
     * @return \Hyperf\Database\Model\Collection|static[]
     */
    public function getAllRoutesOfRole($roleId)
    {
        return $this->buildQuery(['role_id' => $roleId])->get(['id', 'route_id']);
    }

    /**
     * 删除角色的某些路由
     * @param $roleId
     * @param $routeIds
     * @return int
     */
    public function delSomeRouteOfRole($roleId, $routeIds)
    {
        return $this->buildQuery(['role_id' => $roleId,])
            ->whereIn('route_id', $routeIds)
            ->update([
                'deleted_at' => time(),
            ]);
    }

    /**
     * @param array $roleIds
     */
    public function getRouteIdsOfSomeRole($roleIds)
    {
        return $this->buildQuery()->whereIn('role_id', $roleIds)->pluck('route_id');
    }

    /**
     * 删除角色的所有路由绑定关系
     * @param array $roleIds
     * @return int
     */
    public function delRoleAllRoute($roleIds)
    {
        return $this->buildQuery()
            ->whereIn('role_id', $roleIds)
            ->update([
                'deleted_at' => time(),
            ]);
    }

    /**
     * @param $roleId
     * @param $routeId
     * @return bool
     */
    public function roleHasRoute($roleId, $routeId)
    {
        return (bool)$this->buildQuery([
            'role_id' => $roleId,
            'route_id' => $routeId
        ])
            ->first(['id']);
    }

    public function anyRoleHasRoute($roleIds, $routeId)
    {
        return (bool)$this->buildQuery([
            'route_id' => $routeId,
        ])
            ->whereIn('role_id', $roleIds)
            ->first(['id']);
    }
}